<?php
/**
 * Created by PhpStorm.
 * User: aoxiangli
 * Date: 2016/3/30
 * Time: 15:24
 * Description:公共工具类库
 */
defined('BASEPATH') OR exit('No direct script access allowed');

class Tools
{
    private $CI;
    private $uploadAllow = array('pic' => 'gif|jpg|png|jpeg');
    private $typeAllow = array('pic');

    public function __construct()
    {
        $this->CI =& get_instance();
    }

    /**
     * 获取salt
     * @param int $length
     * @return string
     */
    public function getTheSalt($length = 8)
    {
        $str = "abcdefghijklmnopqrstuvwyzABCDEFGHIJKLMNOPQRSTUVWYZ0123456789";
        $str_length = mb_strlen($str);
        $salt = "";
        for ($i = 0; $i < $length; $i++) {
            $rand = rand(0, $str_length - 1);
            $salt .= $str[$rand];
        }
        return $salt;
    }

    /**
     * 增加系统日志
     * @param $event
     */
    public function eventLogs($event)
    {
        $uid = $this->CI->session->adminUser['uid'];
        $data = array('uid' => $uid, 'record' => $event);
        $this->CI->db->insert('operation_logs', $data);
    }

    /**
     * cur查询
     * @param $url
     * @param array $argument
     * @param int $ttl
     * @param string $method
     * @param string $cookie
     * @param int $follow
     * @return array
     */
    public function makeRequest($url, $argument = array(), $ttl = 300, $method = "GET", $cookie = '', $follow = 0, $_headers = array(), $userPwd = "")
    {
        if (!$url) {
            throw new LogicException('$url不能为空');
        }

        if (substr($url, 0, 7) != 'http://' && substr($url, 0, 8) != 'https://') {
            return array('result' => NULL, 'code' => '400');
        }
        if ($method == 'GET' && count($argument) > 0) {
            $url .= "?" . (http_build_query($argument));
            //echo $url;
        }
        if (!$_headers) {
            $header = array(
                'Accept-Language: zh-cn,zh;q=0.8',
                'Connection: Keep-alive',
                'Cache-Control: max-age=0'
            );
        } else {
            $header = $_headers;
        }

        $SSL = substr($url, 0, 8) == "https://" ? true : false;
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        if ($method == 'POST') {
            curl_setopt($ch, CURLOPT_POST, true);
            @curl_setopt($ch, CURLOPT_POSTFIELDS, $argument);
        }
        if (file_exists($cookie)) {
            curl_setopt($ch, CURLOPT_COOKIEJAR, $cookie);
            curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie);
        }
        //   curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
        curl_setopt($ch, CURLOPT_ENCODING, 'gzip');
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_TIMEOUT, $ttl);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/33.0.1707.0 Safari/537.36');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        if ($follow == 1) {
            curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        }
        if ($SSL) {
            curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); // 信任任何证书
            //  curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 1); // 检查证书中是否设置域名
        }
        if ($userPwd) {
            curl_setopt($ch, CURLOPT_USERPWD, $userPwd);
        }
        $return = array();
        $return['url'] = $url;
        $return['result'] = curl_exec($ch);
        $return['code'] = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);
        unset($ch);
        return $return;
    }

    //输出返回数据
    public function echoJson($errorCode, $data = array())
    {

        header('Content-Type: application/json;charset=utf-8');
        $returnJson = array("code" => $errorCode['code'], "result" => $data);
        echo json_encode($returnJson, JSON_UNESCAPED_UNICODE);
        exit;
    }

    //创建文件夹
    public function createDir($dir)
    {
        return is_dir($dir) or
        ($this->createDir(dirname($dir)) and mkdir($dir, 0777));
    }

    //获取网页token
    public function getToken($pre_token)
    {
        $token = md5($this->getTheSalt(16) . time());
        $key = $pre_token . $token;
        $this->CI->cache->redis->save($key, $token, 1800);
        return $token;
    }

    //检查网页token是否正确
    public function checkToken($pre_token)
    {
        $token = $this->CI->input->post("token") != null ? $this->CI->input->post("token") : "";
        return true;
        if (!$token) {
            $this->echoJson($this->CI->errorcode->tokenWrong);
        }
        if (!$this->CI->cache->redis->get($pre_token . $token)) {
            $this->echoJson($this->CI->errorcode->tokenWrong);
        }
    }

    //保存图片
    public function savePic($pic, $type, $size)
    {
        if (!in_array($type, $this->typeAllow)) {
            $this->CI->tools->echoJson($this->CI->errorcode->noReasonWrong);
        }
        $path = '/uploads/' . $type . "/" . date("Y/m/d") . "/";
        $config['upload_path'] = FCPATH . $path;
        $this->createDir($config['upload_path']);
        $config['allowed_types'] = $this->uploadAllow[$type];
        $config['max_size'] = $size;
        $config['encrypt_name'] = true;
        $this->CI->load->library('upload', $config);
        if (!$this->CI->upload->do_upload($pic)) {
            $error = $this->CI->upload->display_errors();
            if (strpos($error, "The image you are attempting to upload doesn't fit into the allowed dimensions.") !== false) {
                $this->echoJson($this->CI->errorcode->noMatchDimension);
            } else if (strpos($error, "You did not select a file to upload") !== false) {
                return array('', 0, 0);
            } else {
                $this->echoJson($this->CI->errorcode->noReasonWrong);
            }
        } else {
            $uploadData = $this->CI->upload->data();
           $url = $path . $uploadData['file_name'];
            return array($url, $uploadData['image_width'], $uploadData['image_height']);
        }
    }
}
